import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Form, 
  Input, 
  Select, 
  Button, 
  message, 
  Card,
  Space,
  Typography
} from 'antd';
import { 
  SaveOutlined, 
  ArrowLeftOutlined,
  BookOutlined
} from '@ant-design/icons';
import { FormCard } from '@/components/common';
import { ProblemSet, CreateProblemSetRequest, UpdateProblemSetRequest } from '@/types/problemSet';
import { problemSetService } from '@/services/problemSetService';
import { accountService } from '@/services/accountService';
import { Team } from '@/types/account';
import MDEditor from '@/components/MDEditor';

const { Option } = Select;
const { TextArea } = Input;
const { Title } = Typography;

interface ProblemSetEditProps {
  isAdmin?: boolean;
  basePath?: string;
}

const ProblemSetEdit: React.FC<ProblemSetEditProps> = ({ 
  isAdmin = false,
  basePath = '/problem' 
}) => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [problemSet, setProblemSet] = useState<ProblemSet | null>(null);
  const [teams, setTeams] = useState<Team[]>([]);
  const [teamsLoading, setTeamsLoading] = useState(false);
  const isEdit = !!id;

  // 获取团队列表
  const fetchTeams = async () => {
    try {
      setTeamsLoading(true);
      const response = await accountService.getTeams();
      const teamsData = response.data?.results || [];
      setTeams(teamsData);
    } catch (error) {
      console.warn('获取团队列表失败:', error);
      // 不显示错误消息，因为团队列表不是必需的
    } finally {
      setTeamsLoading(false);
    }
  };

  // 获取题单详情（编辑模式）
  const fetchProblemSet = async () => {
    if (!id) return;
    
    try {
      setLoading(true);
      const response = await problemSetService.getProblemSet(parseInt(id));
      const data = response.data.data;
      setProblemSet(data);
      
      // 设置表单初始值
      form.setFieldsValue({
        title: data.title,
        description: data.description,
        content: data.content,
        visibility: data.visibility,
        team: data.team,
      });
    } catch (error) {
      message.error('获取题单详情失败');
      navigate(`${basePath}/problem-sets`);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 获取团队列表（创建和编辑都需要）
    fetchTeams();
    
    // 如果是编辑模式，获取题单详情
    if (isEdit) {
      fetchProblemSet();
    }
  }, [id]);

  // 监听可见性变化，当选择公开时清空团队选择
  useEffect(() => {
    const visibility = form.getFieldValue('visibility');
    if (visibility === 'public') {
      form.setFieldValue('team', undefined);
    }
  }, [form.getFieldValue('visibility')]);

  // 获取当前可见性值
  const currentVisibility = Form.useWatch('visibility', form);

  const handleSubmit = async (values: any) => {
    try {
      setSaving(true);
      
      if (isEdit && id) {
        // 更新题单
        const updateData: UpdateProblemSetRequest = {
          title: values.title,
          description: values.description,
          content: values.content,
          visibility: values.visibility,
        };
        
        // 只有当选择了团队时才添加team字段
        if (values.team) {
          updateData.team = values.team;
        }
        
        await problemSetService.updateProblemSet(parseInt(id), updateData);
        message.success('更新成功');
      } else {
        // 创建题单
        const createData: CreateProblemSetRequest = {
          title: values.title,
          description: values.description,
          content: values.content,
          visibility: values.visibility,
        };
        
        // 只有当选择了团队时才添加team字段
        if (values.team) {
          createData.team = values.team;
        }
        
        const response = await problemSetService.createProblemSet(createData);
        message.success('创建成功');
        
        // 跳转到新创建的题单详情页
        navigate(`${basePath}/problem-set/${response.data.data.id}`);
        return;
      }
      
      // 编辑模式下跳转回详情页
      navigate(`${basePath}/problem-set/${id}`);
    } catch (error: any) {
      if (error.response?.data?.data) {
        // 显示具体的字段错误
        const fieldErrors = error.response.data.data;
        Object.keys(fieldErrors).forEach(field => {
          message.error(`${field}: ${fieldErrors[field].join(', ')}`);
        });
      } else {
        message.error(isEdit ? '更新失败' : '创建失败');
      }
    } finally {
      setSaving(false);
    }
  };

  const handleCancel = () => {
    if (isEdit) {
      navigate(`${basePath}/problem-set/${id}`);
    } else {
      navigate(`${basePath}/problem-sets`);
    }
  };

  if (loading) {
    return <div>加载中...</div>;
  }

  return (
    <div>
      <FormCard
        title={
          <Space>
            <BookOutlined />
            {isEdit ? '编辑题单' : '创建题单'}
          </Space>
        }
        extra={
          <Button
            icon={<ArrowLeftOutlined />}
            onClick={handleCancel}
          >
            返回
          </Button>
        }
        form={form}
        onFinish={handleSubmit}
        onCancel={handleCancel}
        submitText={isEdit ? '更新题单' : '创建题单'}
        cancelText="取消"
        loading={saving}
        formProps={{
          layout: "vertical",
          initialValues: {
            visibility: 'public',
          }
        }}
      >
          <Form.Item
            name="title"
            label="题单标题"
            rules={[
              { required: true, message: '请输入题单标题' },
              { max: 100, message: '标题不能超过100个字符' }
            ]}
          >
            <Input placeholder="请输入题单标题" />
          </Form.Item>

          <Form.Item
            name="description"
            label="题单描述"
            rules={[
              { required: true, message: '请输入题单描述' },
              { max: 500, message: '描述不能超过500个字符' }
            ]}
          >
            <TextArea 
              placeholder="请输入题单描述" 
              rows={3}
              showCount
              maxLength={500}
            />
          </Form.Item>

          <Form.Item
            name="content"
            label="题单内容"
            rules={[
              { required: true, message: '请输入题单内容' }
            ]}
            extra="💡 提示：支持从语雀、Typora、Obsidian、Notion等平台复制内容，编辑器会自动将HTML转换为Markdown格式"
          >
            <MDEditor 
              height={500}
              placeholder="请输入题单内容，支持Markdown格式，可以从其他应用复制Markdown内容"
            />
          </Form.Item>

          <Form.Item
            name="visibility"
            label="可见性"
            rules={[
              { required: true, message: '请选择可见性' }
            ]}
          >
            <Select placeholder="请选择可见性">
              <Option value="public">公开 - 所有用户可见</Option>
              <Option value="team">团队 - 仅团队成员可见</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="team"
            label="所属团队"
            dependencies={['visibility']}
          >
            <Select 
              placeholder="请选择团队（可选）"
              allowClear
              loading={teamsLoading}
              disabled={currentVisibility !== 'team'}
            >
              {teams.map(team => (
                <Option key={team.id} value={team.id}>
                  {team.name} ({team.member_count}人) - {team.creator_name}
                </Option>
              ))}
            </Select>
          </Form.Item>
      </FormCard>

      {/* 帮助信息 */}
      <Card size="small" style={{ marginTop: 16 }}>
        <Title level={5}>帮助信息</Title>
        <div>
          <p><strong>题单标题：</strong>简洁明了地描述题单的主题</p>
          <p><strong>题单描述：</strong>简要介绍题单的内容和适用对象</p>
          <p><strong>题单内容：</strong>详细的教学内容，使用Markdown编辑器，支持：</p>
          <ul>
            <li>实时预览Markdown效果</li>
            <li>智能粘贴：从语雀、Typora、Obsidian、Notion等平台复制内容，自动转换为Markdown</li>
            <li>图片上传和插入</li>
            <li>数学公式支持（LaTeX）</li>
            <li>代码高亮显示</li>
            <li>表格、链接、图片等元素的自动转换</li>
            <li>知识点介绍、学习目标、解题思路等</li>
          </ul>
          <p><strong>可见性：</strong></p>
          <ul>
            <li><strong>公开：</strong>所有用户都可以查看和使用</li>
            <li><strong>团队：</strong>只有指定团队的成员可以查看，需要选择具体的团队</li>
          </ul>
        </div>
      </Card>
    </div>
  );
};

export default ProblemSetEdit; 